<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <div class="schema-form">
    <div
      v-for="(propertyObject, propertyName) in jsonSchema.properties"
      :key="propertyName"
      class="form-group"
    >
      <SchemaForm
        v-if="propertyObject.type=='object'"
        :json-schema="propertyObject"
        :name-prefix="propertyName"
      />
      <template v-else>
        <label :for="propertyName">
          {{ propertyObject.title }}
          {{ isRequired(propertyName) ? '*' : '' }}
        </label>
        <SchemaFormWidget
          :id="propertyName"
          :name="withPrefix(propertyName)"
          :property="propertyObject"
          :required="isRequired(propertyName)"
        />
      </template>
    </div>
  </div>
</template>

<script>
import SchemaFormWidget from './SchemaFormWidget.vue';

export default {
  name: 'SchemaForm',
  components: {
    SchemaFormWidget,
  },
  props: {
    jsonSchema: {
      type: Object,
      required: true,
    },
    namePrefix: {
      type: String,
      default: null,
    },
  },
  methods: {
    isRequired(propertyName) {
      return ('required' in this.jsonSchema) && this.jsonSchema.required.includes(propertyName);
    },
    withPrefix(propertyName) {
      return this.namePrefix ? `${this.namePrefix}.${propertyName}` : propertyName;
    },
  },
};
</script>
